package cn.bonoon.controllers.schedule;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bonoon.core.plugins.HolidayService;
import cn.bonoon.core.plugins.PersonalHolidayService;
import cn.bonoon.core.plugins.ScheduleService;
import cn.bonoon.entities.plugins.PersonalHolidayEntity;
import cn.bonoon.entities.plugins.ScheduleEntity;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.models.JsonResult;

/**
 * 日程安排-周视图
 * @author ocean~
 */
@Controller
@RequestMapping("s/user/schedule")
public class ScheduleWeekViewController extends AbstractSchedule {
	
	@Autowired
	public ScheduleWeekViewController(HolidayService holidayService, PersonalHolidayService personalHolidayService, ScheduleService scheduleService) {
		super(holidayService, personalHolidayService, scheduleService);
	}
	
	@RequestMapping("!{key}/index.do")
	public String get(Model model, @PathVariable("key") String key) {
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int date = cal.get(Calendar.DATE);
		model.addAttribute("content", viewWeek(year, month, date));
		return "user/schedule/schedule-view-week";
	}
	
	@RequestMapping(value = "view/week", method = { POST, GET })
	public String weekView(Model model, HttpServletRequest request, Integer year, Integer month, Integer date) {
		Calendar cal = Calendar.getInstance();
		if (null == year) {
			year = cal.get(Calendar.YEAR);
		}
		if (null == month && null == date) { // year_view -> week_view
			if (year == cal.get(Calendar.YEAR)) {
				month = cal.get(Calendar.MONTH);
				date = cal.get(Calendar.DATE);
			} else {
				month = 0;
				date = 1;
			}
		} else if (null != month && null == date) { // month_view -> week_view
			date = year == cal.get(Calendar.YEAR) && month == cal.get(Calendar.MONTH) ? cal.get(Calendar.DATE) : 1;
		}
		model.addAttribute("content", viewWeek(year, month, date));
		return "user/schedule/schedule-view-week";
	}
	
	@ResponseBody
	@RequestMapping(value = "view/refresh_week", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult refresh_weekView(Model model, Integer year, Integer month, Integer date, Boolean next) {
		Calendar cal = Calendar.getInstance();
		if (null == year) {
			year = Calendar.getInstance().get(Calendar.YEAR);
		}
		if (null == month && null == date) { // year_view -> week_view
			if (year == cal.get(Calendar.YEAR)) {
				month = cal.get(Calendar.MONTH);
				date = cal.get(Calendar.DATE);
			} else {
				month = 0;
				date = 1;
			}
		} else if (null != month && null == date) { // month_view -> week_view
			date = year == cal.get(Calendar.YEAR) && month == cal.get(Calendar.MONTH) ? cal.get(Calendar.DATE) : 1;
		}
		if (null != next) {
			cal.set(year, month, date);
			cal.add(Calendar.DATE, next ? 7 : -7);
			year = cal.get(Calendar.YEAR);
			month = cal.get(Calendar.MONTH);
			date = cal.get(Calendar.DATE);
		}
		return JsonResult.result(viewWeek(year, month, date));
	}
	
	@ResponseBody
	@RequestMapping(value = "view/week_today", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult view_week_today(Model model) {
		Calendar cal = Calendar.getInstance();
		return JsonResult.result(viewWeek(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)));
	}
	
	private void add_holidays(List<Calendar> holidays, int year, int month, String m_days) {
		if (StringHelper.isNotEmpty(m_days)) {
			int[] days = StringHelper.tointArray(m_days);
			for (int day : days) {
				Calendar c = Calendar.getInstance();
				c.set(year, month, day);
				holidays.add(c);
			}
		}
	}
	
	private String viewWeek(int year, int month, int date) {
		StringBuilder content = new StringBuilder();
		// -------------------- thead --------------------
		Calendar[] cals = new Calendar[7];
		String[] month_date = new String[7];
		int week = 0;
		for (int i = 0; i < 7; i++) {
			cals[i] = Calendar.getInstance();
			cals[i].set(year, month, date);
			if (i == 0) {
				week = cals[0].get(Calendar.DAY_OF_WEEK);
			}
			cals[i].add(Calendar.DATE, i + 1 - week);
			month_date[i] = cals[i].get(Calendar.MONTH) + 1 + "/" + cals[i].get(Calendar.DATE);
		}
		int start_year = cals[0].get(Calendar.YEAR);
		int start_month = cals[0].get(Calendar.MONTH);
		int start_date = cals[0].get(Calendar.DATE);
		int end_year = cals[6].get(Calendar.YEAR);
		int end_month = cals[6].get(Calendar.MONTH);
		int end_date = cals[6].get(Calendar.DATE);

		content.append("<tr>");
		content.append("<td colspan='7' style='text-align:center;height:50px;'>");//text-align:right;position:relative;
		content.append("<span style='float:left;'>");
		content.append("<a href='#' class='bupabutton' data-settings='flat:true' id='a_today'>今天</a>&nbsp;");//position:absolute;left:0;
		content.append("<a href='#' class='bupabutton' data-settings='flat:true' id='a_lastWeek'>上一周</a>");
		content.append("<a href='#' class='bupabutton' data-settings='flat:true' id='a_nextWeek'>下一周</a>");
		content.append("</span>");
		content.append("<strong><span style='font-size:16px;'><span id='title_year_start'>").append(start_year).append("</span>年");
		content.append("<span id='title_month_start' style='display:inline-block;width:18px;'>").append(start_month + 1).append("</span>月");
		content.append("<span id='title_date_start' style='display:inline-block;width:18px;'>").append(start_date).append("</span>日—");
		content.append("<span id='title_year_end'>").append(end_year).append("</span>年");
		content.append("<span id='title_month_end' style='display:inline-block;width:18px;'>").append(end_month + 1).append("</span>月");
		content.append("<span id='title_date_end' style='display:inline-block;width:18px;'>").append(end_date);
		content.append("</span>日行程安排</span></strong>");
		content.append("<span style='float:right;'>");
		content.append("<img src='/res/images/holiday.png'/>：公共节假日&nbsp;&nbsp;");
		content.append("<img src='/res/images/windmill.png'/>：个人假日&nbsp;&nbsp;");
		content.append("<img src='/res/images/detail.png' />：行程日志&nbsp;&nbsp;&nbsp;");
		content.append("<a href=\"#\" class=\"bupabutton\" data-settings='flat:true' id=\"a_weekview\" data-settings=\"selected:true\">&nbsp;周&nbsp;</a>");
		content.append("<a href=\"#\" class=\"bupabutton\" data-settings='flat:true' id=\"a_monthview\">&nbsp;月&nbsp;</a>");
		content.append("<a href=\"#\" class=\"bupabutton\" data-settings='flat:true' id=\"a_yearview\">&nbsp;年&nbsp;</a>");
		content.append("</span></td></tr>");
		content.append("<tr>");
		content.append("<th style='width:100px;text-align:center;'>日&nbsp;&nbsp;").append(month_date[0]).append("</th>");
		content.append("<th style='width:100px;text-align:center;'>一&nbsp;&nbsp;").append(month_date[1]).append("</th>");
		content.append("<th style='width:100px;text-align:center;'>二&nbsp;&nbsp;").append(month_date[2]).append("</th>");
		content.append("<th style='width:100px;text-align:center;'>三&nbsp;&nbsp;").append(month_date[3]).append("</th>");
		content.append("<th style='width:100px;text-align:center;'>四&nbsp;&nbsp;").append(month_date[4]).append("</th>");
		content.append("<th style='width:100px;text-align:center;'>五&nbsp;&nbsp;").append(month_date[5]).append("</th>");
		content.append("<th style='width:100px;text-align:center;'>六&nbsp;&nbsp;").append(month_date[6]).append("</th>");
		content.append("</tr>");
		// -------------------- tbody --------------------
		List<PersonalHolidayEntity> personalHolidays = personalHolidayService.getWeek(getUser(), cals[0], cals[6]);
		List<ScheduleEntity> schedules = scheduleService.getWeek(getUser(), year, month, date);
		List<Calendar> holidays = new ArrayList<Calendar>();
		boolean same_year = start_year == end_year;
		boolean same_month = start_month == end_month;
		if (same_year && same_month) { // 同年同月
			String m_days = holidayService.getMonth(year, month);
			add_holidays(holidays, year, month, m_days);
		} else if (same_year && !same_month) { // 同年跨月
			Object obj = holidayService.get2Month(start_year, start_month, end_month);
			if (null != obj) {
				Object[] objs = (Object[]) obj;
				if (null != objs[0]) {
					String m_days_start = objs[0].toString();
					add_holidays(holidays, start_year, start_month, m_days_start);
				}
				if (null != objs[1]) {
					String m_days_end = objs[1].toString();
					add_holidays(holidays, end_year, end_month, m_days_end);
				}
			}
		} else if (!same_year && !same_month) { // 跨年跨月
			String m_days_start = holidayService.getMonth(start_year, start_month);
			String m_days_end = holidayService.getMonth(end_year, end_month);
			add_holidays(holidays, start_year, start_month, m_days_start);
			add_holidays(holidays, end_year, end_month, m_days_end);
		}

		int holidays_len = holidays.size();
		int[] tips_sc = new int[7]; // 显示行程安排的数量
		int[] tips_ph = new int[7]; // 显示个人假期的数量
		content.append("<tr>");
		for (int i = 0; i < 7; i++) {
			int y = cals[i].get(Calendar.YEAR);
			int m = cals[i].get(Calendar.MONTH);
			int d = cals[i].get(Calendar.DATE);
			week = cals[i].get(Calendar.DAY_OF_WEEK);
			if (null != holidays && holidays_len != 0) {
				boolean flag = false;
				for (int j = 0; j < holidays_len; j++) {
					Calendar holiday = holidays.get(j);
					if (holiday.get(Calendar.YEAR) == y && holiday.get(Calendar.MONTH) == m && holiday.get(Calendar.DATE) == d) {
						flag = true;
						break;
					}
				}
				if (flag) {
					content.append("<td style='text-align:left;cursor:default;position:relative;height:500px;' valign='top' class='day selectedDay'>");
				} else {
					content.append("<td style='text-align:left;cursor:default;position:relative;height:500px;' valign='top' class='day'>");
				}
			} else {
				if (week == 1 || week == 7) {
					content.append("<td style='text-align:left;cursor:default;position:relative;height:500px;' valign='top' class='day selectedDay'>");
				} else {
					content.append("<td style='text-align:left;cursor:default;position:relative;height:500px;' valign='top' class='day'>");
				}
			}
			content.append("<input type='hidden' class='").append(y).append("-").append(m).append("' value='").append(d).append("' />"); // class='yyyy-mm'
			content.append(d).append("<br/><br/>");
			// 当天是否存在行程安排
			if (null != schedules) {
				boolean img_flag = false;
				for (int j = schedules.size() - 1; j >= 0; j--) {
					ScheduleEntity s = schedules.get(j);
					Calendar executeAt = Calendar.getInstance();
					executeAt.setTime(s.getExecuteAt());
					boolean hasSchedules = executeAt.get(Calendar.YEAR) == y && executeAt.get(Calendar.MONTH) == m && executeAt.get(Calendar.DATE) == d;
					if (!img_flag && hasSchedules) {
						content.append("<img src='/res/images/detail.png' name='img_schedule' style='position:absolute;right:40px;top:0;'/>");
						content.append("行程安排：<br/>");
						img_flag = true;
					}
					if (hasSchedules && tips_sc[i] < 10) {
						String name = s.getName();
						name = name.length() > 11 ? name.substring(0, 11) + "..." : name;
						content.append(name).append("<br/>");
						tips_sc[i]++;
					}
				}
//				for (ScheduleEntity s : schedules) {
//					Calendar executeAt = Calendar.getInstance();
//					executeAt.setTime(s.getExecuteAt());
//					if (executeAt.get(Calendar.YEAR) == y && executeAt.get(Calendar.MONTH) == m && executeAt.get(Calendar.DATE) == d) {
//						content.append("<img src='/res/images/detail.png' name='img_schedule' style='position:absolute;right:40px;top:0;'/>");
//						break;
//					}
//				}
			}
			// 当天是否开始个人假日（持续N天）
			if (null != personalHolidays) {
				boolean img_flag = false;
				for (int j = personalHolidays.size() - 1; j >= 0 ; j--) {
					PersonalHolidayEntity ph = personalHolidays.get(j);
					boolean hasPh = ph.getYear() == y && ph.getMonth() == m && ph.getDate() == d;
					if (!img_flag && hasPh) {
						content.append("<img src='/res/images/windmill.png' name='img_personalHoliday' style='position:absolute;right:20px;top:0;' />");
						content.append("<span style='position:absolute;bottom:0;height:155px;'>");
						content.append("个人假期：<br/>");
						img_flag = true;
					}
					if (hasPh && tips_ph[i] < 5) {
						int type = ph.getType();//（0.请假/事假； 1.病假； 2.年假； 3.加班； 4.缺席；）
						String tips = type == 0 ? "请假/事假" : type == 1 ? "病假" : type == 2 ? "年假" : type == 3 ? "加班" : type == 4 ? "缺席" : "其它";
						tips = tips.length() > 11 ? tips.substring(0, 11) + "..." : tips;
						content.append(tips).append("<br/>");
						tips_ph[i]++;
					}
				}
				if (tips_ph[i] != 0) {					
					content.append("<br/></span>");
				}
//				for (PersonalHolidayEntity ph : personalHolidays) {
//					if (ph.getYear() == y && ph.getMonth() == m && ph.getDate() == d) {
//						content.append("<img src='/res/images/windmill.png' name='img_personalHoliday' style='position:absolute;right:20px;top:0;' />");
//						break;
//					}
//				}
			}
			content.append("</td>");
		}
		content.append("</tr>");
		content.append("<input id='year' type='hidden' value='").append(year).append("'/>");
		content.append("<input id='month' type='hidden' value='").append(month).append("'/>");
		content.append("<input id='date' type='hidden' value='").append(date).append("'/>");
		return content.toString();
	}
}
